//http://www.java-samples.com/showtutorial.php?tutorialid=152

package microarray;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.io.*;

import javax.jdo.annotations.Persistent;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;

import com.google.appengine.api.datastore.Key;

import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

@PersistenceCapable
public class ESearch extends EUtil  implements Serializable{
	/**
	 * 
	 */
	private static final long serialVersionUID = 8267909369306201587L;
	@PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
	private Key key;
	
	@Persistent
	private List<String> ids;
	@Persistent
	private String webEnv;
	@Persistent
	private String queryKey;
	
	private String textValue;
	private int count;
    public ESearch(Map<String, String> args) throws Exception {
    	ids = new LinkedList<String>();
    	parseData(openInput("http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?", args));
    }
    
    public List<String> getIDs()
    {
    	return ids;
    } 
    
    public String getWebEnv()
    {
    	return webEnv;
    }
    
    public String getQueryKey()
    {
    	return queryKey;
    }

	@Override
	public void parseData(InputStream in) throws Exception {
		//get a factory
		SAXParserFactory spf = SAXParserFactory.newInstance();
		try {

			//get a new instance of parser
			SAXParser sp = spf.newSAXParser();

			//parse the file and also register this class for call backs
			sp.parse(in, this);

		}catch(SAXException se) {
			se.printStackTrace();
		}catch(ParserConfigurationException pce) {
			pce.printStackTrace();
		}catch (IOException ie) {
			ie.printStackTrace();
		}
	}
	
	//Event Handlers
	public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {

	}
	

	public void characters(char[] ch, int start, int length) throws SAXException {
		textValue = new String(ch,start,length);
	}
	
	public void endElement(String uri, String localName, String qName) throws SAXException {
		if(qName.equalsIgnoreCase("Count")) {
			count = Integer.parseInt(textValue);
		}
		else if (qName.equals("WebEnv")){
			webEnv = textValue;
		}
		else if (qName.equals("QueryKey")){
			queryKey = textValue;
		}
		else if (qName.equals("Id")){
			ids.add(textValue);
		}
	}
	
	public String toString()
	{
		String out = webEnv;
		out += "\n" + queryKey;
		for (String id : ids)
			out += id + "\n";
		return out;
	}


    
}



	
	

